"""
数据模型定义
"""
import uuid
from datetime import datetime
from sqlalchemy import Column, String, DateTime, Integer, Text, JSON, Boolean, ForeignKey, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class Workspace(Base):
    """工作区模型"""
    __tablename__ = 'workspaces'
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    name = Column(String(255), nullable=False)
    description = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    is_active = Column(Boolean, default=True)
    
    # 工作区设置
    settings = Column(JSON, default={})
    
    # 关联关系
    analysis_sessions = relationship("AnalysisSession", back_populates="workspace", cascade="all, delete-orphan")
    
    def to_dict(self):
        return {
            'id': str(self.id),
            'name': self.name,
            'description': self.description,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'is_active': self.is_active,
            'settings': self.settings
        }

class AnalysisSession(Base):
    """分析会话模型"""
    __tablename__ = 'analysis_sessions'
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    workspace_id = Column(String(36), ForeignKey('workspaces.id'), nullable=False)
    name = Column(String(255), nullable=False)
    description = Column(Text)
    
    # 会话状态
    status = Column(String(50), default='created')  # created, analyzing, completed, failed
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 文件信息
    original_filename = Column(String(255))
    file_size = Column(Integer)
    file_hash = Column(String(64))
    storage_path = Column(String(500))
    
    # 分析结果
    analysis_results = Column(JSON)
    ai_analysis = Column(JSON)
    
    # 元数据
    tags = Column(JSON, default=[])
    bookmarks = Column(JSON, default=[])
    notes = Column(Text)
    
    # 关联关系
    workspace = relationship("Workspace", back_populates="analysis_sessions")
    conversations = relationship("Conversation", back_populates="session", cascade="all, delete-orphan")
    
    def to_dict(self):
        return {
            'id': str(self.id),
            'workspace_id': str(self.workspace_id),
            'name': self.name,
            'description': self.description,
            'status': self.status,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'original_filename': self.original_filename,
            'file_size': self.file_size,
            'file_hash': self.file_hash,
            'storage_path': self.storage_path,
            'analysis_results': self.analysis_results,
            'ai_analysis': self.ai_analysis,
            'tags': self.tags,
            'bookmarks': self.bookmarks,
            'notes': self.notes
        }

class Conversation(Base):
    """对话历史模型"""
    __tablename__ = 'conversations'
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    session_id = Column(String(36), ForeignKey('analysis_sessions.id'), nullable=False)
    
    # 对话内容
    message_type = Column(String(20), nullable=False)  # user, ai, system
    content = Column(Text, nullable=False)
    timestamp = Column(DateTime, default=datetime.utcnow)
    
    # 上下文信息
    context = Column(JSON)
    
    # 关联关系
    session = relationship("AnalysisSession", back_populates="conversations")
    
    def to_dict(self):
        return {
            'id': str(self.id),
            'session_id': str(self.session_id),
            'message_type': self.message_type,
            'content': self.content,
            'timestamp': self.timestamp.isoformat(),
            'context': self.context
        }

class UserConfig(Base):
    """用户配置模型"""
    __tablename__ = 'user_configs'
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    workspace_id = Column(String(36), ForeignKey('workspaces.id'), nullable=False)
    
    # 配置类型
    config_type = Column(String(50), nullable=False)  # rules, ai_config, ui_preferences
    config_data = Column(JSON, nullable=False)
    
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        return {
            'id': str(self.id),
            'workspace_id': str(self.workspace_id),
            'config_type': self.config_type,
            'config_data': self.config_data,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }
